package com.fangfaze.java.hcwork.liveLifeCycle.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class UrlSignUtil {

    public static String generate(String scheme, String host, String applicationId, String streamId, String key, String timeStamp) {

        String path = String.format("/%s/%s", applicationId, streamId);
        String signKey = md5(String.format("%s-%s-0-0-%s", path, timeStamp, key));
        return String.format("%s%s%s?auth_key=%s-0-0-%s", scheme, host, path, timeStamp, signKey);
    }

    public static String md5(String string) {
        if (string.isEmpty()) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes("UTF-8"));
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }
}
